package seekting.demo2017.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.seekting.demo_lib.Demo;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.nio.CharBuffer;

/**
 * Created by seekting on 17-7-6.
 */
@Demo(title = "管道通讯")
public class PipeActivity extends Activity {

    PipedWriter mPipedWriter;
    PipedReader mPipedReader;
    private Thread mT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPipedWriter = new PipedWriter();
        mPipedReader = new PipedReader();
        try {
            mPipedWriter.connect(mPipedReader);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Button button = new Button(this);
        setContentView(button);

        button.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                String str = "hello";
                try {
                    mPipedWriter.write(str, 0, str.length());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        mT = new Thread(new Runnable() {
            @Override
            public void run() {

                CharBuffer charBuffer = CharBuffer.allocate(200);
                int i;
                while (true && !mT.isInterrupted()) {

                    try {
                        i = mPipedReader.read(charBuffer);
                        if (i == -1) {
                            break;
                        }
                        charBuffer.flip();
                        Log.d("seekting", "PipeActivity.run()" + String.valueOf(charBuffer.toString()));
                    } catch (IOException e) {
                        e.printStackTrace();


                        Log.d("seekting", "PipeActivity.run() isInterrupted=" + mT.isInterrupted());
                    }
                }
                Log.d("seekting", "PipeActivity.run() over!");

            }
        });
        mT.start();


    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        return super.onRetainNonConfigurationInstance();
    }

    @Nullable
    @Override
    public Object getLastNonConfigurationInstance() {
        return super.getLastNonConfigurationInstance();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //先关闭writer，这样会read到-1，线程死亡
        try {
            mPipedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mPipedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        mT.interrupt();
    }
}
